<!--
 * @Author: gonghairun
 * @Date: 2020-11-19 10:16:14
 * @LastEditors: zhangzhanhua
 * @LastEditTime: 2021-05-03 15:39:56
 * @Description: //描述
-->
<template>
    <div class="receiptManagePage">
        <div class="searchTop">
            <div class="topContent">
                <el-tooltip class="item" effect="dark" content="导入" placement="top" v-if="menuArr.includes('数据导入按钮')">
                    <el-upload
                        ref="upload"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :http-request="uploadFile"
                        name="fileArray"
                        :show-file-list="false">
                            <el-button slot="trigger" size="mini" icon="el-icon-plus"></el-button>
                    </el-upload>
                </el-tooltip>
            </div>
            <div class="topContent">
                <el-tooltip class="item" effect="dark" content="插入数据库" placement="top" v-if="menuArr.includes('插入数据库按钮')">
                    <el-button size="mini" icon="el-icon-s-unfold" @click="handleClick()"></el-button>
                </el-tooltip>
            </div>
        </div>
        <div class="tableContent">
            <BaseTable :loading="isLoading" :data="tableTotalList" :tableHeight="tableHeight" :columns="columns" :pagination="false"></BaseTable>
        </div>
        <!-- 发票详情 -->
        <el-drawer :visible.sync="isShow" title="插入数据库" size="40%" class="fontSize24" :before-close="handleClose">
            <div class="drawerContent" >
                <detailPage v-if="isShow" :schemasTableChangeIndex="schemasTableChangeIndex" :schemasChangeIndex="schemasChangeIndex" :rules="rules" :formList="formList" :ruleForm="ruleForm" :goBackClick="goBack" :submit="submit"></detailPage>
            </div>
        </el-drawer>
        <div class="saveLoading" v-loading="saveLoading" v-if="saveLoading" element-loading-text="导入中..."></div>
    </div>
</template>

<script>
import BaseTable from "@/components/BaseTable" // 表格
import detailPage from './subPage/detailPage.vue' // 明细页面
export default {
    name: "receiptManagePage",
    components: {
        BaseTable,
        detailPage
    },
    data() {
        return {
            menuArr:[],
            saveLoading:false, //保存loading
            tableHeight:window.innerHeight-200,//表格高度
            isLoading: false, //表格加载状态
            tableList:[],//表格数据
            columns:[],//表头
            isShow:false,//显示弹出层
            tableTotalList:[],
            formList:[
                {
                    prop:'name',
                    label:'数据库',
                    value:''
                },
                {
                    prop:'tableName',
                    label:'表名',
                    value:''
                },
            ],
            ruleForm:{},
            rules:{},
        };
    },
    created() {
    },
    activated() {
        if(this.$store.state.app.searchResouce =="menu"){
            this.columns = []
            this.tableList = []
            this.tableTotalList = []
            this.isLoading = false
        }
        var menuArr = []
        var menuId = ""
        if(localStorage.getItem("menuArr")){
            menuArr = JSON.parse(localStorage.getItem("menuArr"))
        }
        menuArr.map(item=>{
            item.children.map(v=>{
                if(window.location.href.includes(v.url)){
                    menuId = v.id
                }
            })
        })

        if(menuId){
            this.menuArr = []
            this.$http.get(`/${this.$ServiceName}/api/external/sysmenubtn/listresourcebtnbyid?menuId=${menuId}`,{ timeout: 30000,})
                .then(res => {
                    res.data.data.map(item=>{
                        this.menuArr.push(item.resourceName)
                    })
                }).catch((error)=>{})
        }
    },
    watch: {
    },
    mounted() {
    },
    methods: {
        /**
         * @Author: gonghairun
         * @description: 显示弹窗
         * @param {*}
         * @return {*}
         */
        handleClick() {
            let obj = {}
            this.formList.map((item)=>{
                obj[item.prop] = ''
            })
            this.ruleForm = obj
            this.isShow = true
        },
        /**
         * @Author: gonghairun
         * @description: 修改库
         * @param {*}
         * @return {*}
         */
        schemasChangeIndex(){
            Object.keys(this.ruleForm).map((key,index) => {
                if (index != 0) {
                    this.ruleForm[key] = ''
                }
            })
        },
        /**
         * @Author: gonghairun
         * @description: 修改表
         * @param {*}
         * @return {*}
         */
        schemasTableChangeIndex() {
            Object.keys(this.ruleForm).map((key,index) => {
                if (index != 0 && index != 1) {
                    this.ruleForm[key] = ''
                }
            })
        },
        /**
         * @Author: gonghairun
         * @description: 关闭弹窗
         * @param {*} done
         * @return {*}
         */
        handleClose(done) {
            // this.$confirm('确认关闭？').then(_ => {
                done();
                this.isShow = false
            // })
            // .catch(_ => {});
        },
        /**
         * @Author: gonghairun
         * @description: 关闭弹窗
         * @param {*}
         * @return {*}
         */
        goBack() {
            this.isShow = false
        },
        /**
         * @Author: gonghairun
         * @description: 点击确认
         * @param {*} form
         * @return {*}
         */
        submit(form) {
            const _this = this
            _this.saveLoading = true
            let dataList = [],columns = [],dataLength = []
            // 遍历数据插入null
            Object.keys(form).map((key,index) => {
                if (index>1) {
                    dataLength.push(key)
                }
            })
            _this.tableList.map((item)=>{
                // 遍历数据插入null
                Object.keys(item).map((key) => {
                    dataLength.map((childItem,childIndex)=>{
                        if (item[childIndex] == undefined) {
                            item[childIndex] = null
                        }
                    })
                })
            })
            _this.tableList.map((childItem,childIndex)=>{
                let obj = {}
                Object.keys(form).map((key,index) => {
                    Object.keys(childItem).map((key1,index1) => {
                        let newKey = key.includes('key') ? key.replace('key','') : key
                        if (form[key]!='') {
                            if (newKey == key1) {
                                obj[form[key]] = childItem[key1]
                                columns.push(form[key])
                            }
                        }
                    })
                })
                dataList.push(obj)
            })
            let params = {
                schema:form.name,
                table:form.tableName,
                columns:_this.unique(columns),
                listData:dataList
            }
            _this.$http.post(`/psys-import-service/api/external/excelimport/${_this.$version}/importdata`, params).then(res => {
                console.log(res)
                _this.saveLoading = false
                _this.$message.success('导入成功')
                _this.isShow = false
            }).catch(()=>{
                _this.saveLoading = false
            })
        },
        /**
         * @Author: gonghairun
         * @description: 读取excel数据
         * @param {*} params
         * @return {*}
         */
        uploadFile(params) {
            const _this = this
            _this.isLoading = true
            _this.tableList = []
            _this.tableTotalList = []
            let file = params.file;
            let FormDatas = new FormData()
            FormDatas.append('file', file)
            _this.$http.post(`/psys-import-service/api/external/excelimport/${_this.$version}/readexceldata`, FormDatas).then(res => {
                console.log(res)
                let data = res.data.data
                console.log(data)
                let columns = [],tableList = [],formList = []
                _this.formList = [
                    {
                        prop:'name',
                        label:'数据库',
                        value:''
                    },
                    {
                        prop:'tableName',
                        label:'表名',
                        value:''
                    },
                ]
                data.map((item,index)=>{
                    if (index == 0) {
                        Object.keys(item).map(key => {
                            columns.push({
                                prop:key,
                                label:item[key]
                            })
                            formList.push({
                                prop:'key'+key,
                                label:item[key],
                            })
                        })
                    } else {
                        tableList.push(item)
                    }
                })
                _this.columns = columns
                _this.tableList = tableList
                _this.tableTotalList = tableList.length > 20 ? tableList.slice(0,20) : tableList
                _this.$set(_this.tableList[0],'index','')
                _this.$forceUpdate()
                _this.formList = _this.formList.concat(formList)
                let obj = {}
                let rules = {}
                _this.formList.map((item)=>{
                    obj[item.prop] = ''
                    _this.$set(rules,item.prop,{ required: true, message: '请选择'+item.label, trigger: 'change' })
                })
                _this.ruleForm = obj
                // _this.rules = rules
                _this.isLoading = false
                _this.$message.success("上传成功")
            }).catch((error)=>{
                console.log(error)
            })
        },
          /**
         * @name: 去重
         * @author: gonghairun
         * @msg:
         * @param {type}
         * @return {type}
         */
        unique(arr) {
            return Array.from(new Set(arr))
        },
    }
};
</script>

<style lang="less" scoped>
@import "./index.less";
</style>
